<template>
  <el-container>
    <el-header>
      <Search :cateList="cateList" @search="handleSearch" />
    </el-header>
    <el-main>
      <Table
        :cateNameList="cateNameList"
        :total="goodsTotal"
        :current="searchFrom.page"
        :page-size="searchFrom.size"
        :goodsList="goodsList"
        :size="searchFrom.size"
        @pageChange="handleChange"
        @delete="handleDelete"
      />
    </el-main>
  </el-container>
</template>

<script>
import { getCateList, getGoodsList,deleteGoods } from "@/api/products.js";
import Search from "./Components/Search.vue";
import Table from "./Components/Table.vue";
export default {
  components: {
    Search,
    Table,
  },
  data() {
    return {
      cateList: [],
      searchFrom: {
        page: 1,
        size: 20,
        searchWord: "",
        category: "",
      },
      goodsTotal: 0,
      goodsList: [],
    };
  },
  async created() {
    let cateList = (await getCateList({})) || [];
    this.cateList = cateList.data;

    await this.getGoodsListData();
  },
  computed: {
    cateNameList() {
      return this.cateList.map((it) => {
        return {
          key: it.id,
          value: it.name,
        };
      });
    },
  },
  methods: {
    async handleSearch(data, callback) {
      this.searchFrom.category = data.category;
      this.searchFrom.searchWord = data.keywords;
      await this.getGoodsListData();
      callback();
    },
    async handleChange(page) {
      if(page === this.searchFrom.page){
        return;
      }
      this.searchFrom.page = page;
      await this.getGoodsListData();
    },
    async getGoodsListData() {
      let goodsList = await getGoodsList(this.searchFrom);

      this.goodsList = goodsList.data;
      this.goodsTotal = goodsList.total;
    },
    async handleDelete(id){
      await deleteGoods({id})
      await this.getGoodsListData();
    }
  },
};
</script>

<style>
</style>